/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kungkhies.desktop.ilo.editor;

import com.kungkhies.desktop.ilo.explorer.IloExplorerTopComponent;
import com.kungkhies.desktop.library.entities.Ilo;
import java.io.IOException;
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.openide.util.Exceptions;
import org.openide.util.LookupEvent;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.NotifyDescriptor.Confirmation;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.UndoRedo;
import org.openide.cookies.SaveCookie;
import org.openide.explorer.ExplorerManager;
import org.openide.util.Lookup;
import org.openide.util.LookupListener;
import org.openide.util.RequestProcessor;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//com.kungkhies.desktop.ilo.editor//IloEditor//EN",
autostore = false)
@TopComponent.Description(preferredID = "IloEditorTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.kungkhies.desktop.ilo.editor.IloEditorTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_IloEditorAction",
preferredID = "IloEditorTopComponent")
public final class IloEditorTopComponent extends TopComponent implements ExplorerManager.Provider, LookupListener
{
    private static ExplorerManager em = new ExplorerManager();
    private Ilo ilo;
    private UndoRedo.Manager manager = new UndoRedo.Manager();
    private final SaveCookieImpl impl;
    private final InstanceContent content;
    private Lookup.Result result = null;

    public IloEditorTopComponent()
    {
        initComponents();
        setName(NbBundle.getMessage(IloEditorTopComponent.class, "CTL_IloEditorTopComponent"));
        setToolTipText(NbBundle.getMessage(IloEditorTopComponent.class, "HINT_IloEditorTopComponent"));

        iloPackageTextField.getDocument().addUndoableEditListener(manager);
        iloTextArea.getDocument().addUndoableEditListener(manager);
        notesTextArea.getDocument().addUndoableEditListener(manager);

        notesTextArea.getDocument().addDocumentListener(new DocumentListener()
        {
            @Override
            public void insertUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void removeUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void changedUpdate(DocumentEvent arg0)
            {
                fire(true);
            }
        });

        iloTextArea.getDocument().addDocumentListener(new DocumentListener()
        {
            @Override
            public void insertUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void removeUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void changedUpdate(DocumentEvent arg0)
            {
                fire(true);
            }
        });

        iloPackageTextField.getDocument().addDocumentListener(new DocumentListener()
        {
            @Override
            public void insertUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void removeUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void changedUpdate(DocumentEvent arg0)
            {
                fire(true);
            }
        });

        //Create a new instance of our SaveCookie implementation:
        impl = new SaveCookieImpl();

        //Create a new instance of our dynamic object:
        content = new InstanceContent();

        //Add the dynamic object to the TopComponent Lookup:
        associateLookup(new AbstractLookup(content));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        packageLabel = new javax.swing.JLabel();
        iloPackageTextField = new javax.swing.JTextField();
        iloLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        iloTextArea = new javax.swing.JTextArea();
        notesLabel = new javax.swing.JLabel();
        notesScrollPane = new javax.swing.JScrollPane();
        notesTextArea = new javax.swing.JTextArea();
        saveButtton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setPreferredSize(new java.awt.Dimension(781, 777));

        org.openide.awt.Mnemonics.setLocalizedText(packageLabel, org.openide.util.NbBundle.getMessage(IloEditorTopComponent.class, "IloEditorTopComponent.packageLabel.text")); // NOI18N

        iloPackageTextField.setColumns(5);
        iloPackageTextField.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        iloPackageTextField.setText(org.openide.util.NbBundle.getMessage(IloEditorTopComponent.class, "IloEditorTopComponent.iloPackageTextField.text")); // NOI18N
        iloPackageTextField.setMinimumSize(new java.awt.Dimension(6, 35));
        iloPackageTextField.setPreferredSize(new java.awt.Dimension(44, 30));

        org.openide.awt.Mnemonics.setLocalizedText(iloLabel, org.openide.util.NbBundle.getMessage(IloEditorTopComponent.class, "IloEditorTopComponent.iloLabel.text")); // NOI18N

        jScrollPane1.setMaximumSize(new java.awt.Dimension(32767, 30));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(100, 30));

        iloTextArea.setColumns(5);
        iloTextArea.setLineWrap(true);
        iloTextArea.setRows(5);
        iloTextArea.setMaximumSize(new java.awt.Dimension(7483647, 2147483647));
        iloTextArea.setMinimumSize(new java.awt.Dimension(164, 35));
        iloTextArea.setPreferredSize(new java.awt.Dimension(164, 30));
        jScrollPane1.setViewportView(iloTextArea);

        org.openide.awt.Mnemonics.setLocalizedText(notesLabel, org.openide.util.NbBundle.getMessage(IloEditorTopComponent.class, "IloEditorTopComponent.notesLabel.text")); // NOI18N

        notesScrollPane.setPreferredSize(new java.awt.Dimension(100, 30));

        notesTextArea.setColumns(5);
        notesTextArea.setRows(5);
        notesTextArea.setMinimumSize(new java.awt.Dimension(4, 35));
        notesTextArea.setPreferredSize(new java.awt.Dimension(44, 30));
        notesScrollPane.setViewportView(notesTextArea);

        org.openide.awt.Mnemonics.setLocalizedText(saveButtton, org.openide.util.NbBundle.getMessage(IloEditorTopComponent.class, "IloEditorTopComponent.saveButtton.text")); // NOI18N
        saveButtton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                saveButttonMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(IloEditorTopComponent.class, "IloEditorTopComponent.cancelButton.text")); // NOI18N
        cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancelButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(67, 67, 67)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(packageLabel)
                    .addComponent(iloPackageTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 631, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(iloLabel)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 631, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(notesLabel)
                    .addComponent(notesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 631, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(saveButtton)
                        .addGap(18, 18, 18)
                        .addComponent(cancelButton))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(55, 55, 55)
                .addComponent(packageLabel)
                .addGap(10, 10, 10)
                .addComponent(iloPackageTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(41, 41, 41)
                .addComponent(iloLabel)
                .addGap(10, 10, 10)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(42, 42, 42)
                .addComponent(notesLabel)
                .addGap(10, 10, 10)
                .addComponent(notesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(saveButtton)
                    .addComponent(cancelButton)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void saveButttonMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_saveButttonMouseClicked
    {//GEN-HEADEREND:event_saveButttonMouseClicked
        try
        {
            impl.save();
        }
        catch (IOException ex)
        {
            Exceptions.printStackTrace(ex);
        }
    }//GEN-LAST:event_saveButttonMouseClicked

    private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_cancelButtonMouseClicked
    {//GEN-HEADEREND:event_cancelButtonMouseClicked
        clearAndCancel();        // TODO add your handling code here:
    }//GEN-LAST:event_cancelButtonMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel iloLabel;
    private javax.swing.JTextField iloPackageTextField;
    private javax.swing.JTextArea iloTextArea;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel notesLabel;
    private javax.swing.JScrollPane notesScrollPane;
    private javax.swing.JTextArea notesTextArea;
    private javax.swing.JLabel packageLabel;
    private javax.swing.JButton saveButtton;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened()
    {
        RequestProcessor.getDefault().post(new Runnable()
        {
            @Override
            public void run()
            {
                readIlo();
            }
        });
    }

    private void readIlo()
    {
        //JavaDBSupport.ensureStartedDB();
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                TopComponent tc = WindowManager.getDefault().findTopComponent("ILOExplorerTopComponent");
                if (tc == null)
                {
                    System.out.println("ILO Viewer. readILO: top component in get default is null");
                    return;
                }
                result = tc.getLookup().lookupResult(Ilo.class);
                result.addLookupListener(IloEditorTopComponent.this);
                resultChanged(new LookupEvent(result));
            }
        });
    }

    @Override
    public void componentClosed()
    {
        result.removeLookupListener(this);
        result = null;
    }

    void writeProperties(java.util.Properties p)
    {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p)
    {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    public ExplorerManager getExplorerManager()
    {
        return em;
    }

    @Override
    public void resultChanged(LookupEvent le)
    {
        System.out.println("In result changes IloViewerTopComponent.");
        Lookup.Result r = (Lookup.Result) le.getSource();
        Collection<Ilo> coll = r.allInstances();
        if (!coll.isEmpty())
        {
            for (Ilo lo : coll)
            {
                ilo = lo;
                iloPackageTextField.setText(lo.getPackage1());
                iloTextArea.setText(lo.getIloText());

                String notesString = lo.getNote();

                notesTextArea.setText(notesString);
            }
        }
        else
        {
            iloPackageTextField.setText("[no selection]");
            iloTextArea.setText("");
            notesTextArea.setText("");
        }
    }

    public void fire(boolean modified)
    {
        if (modified)
        {
            //If the text is modified,
            //we add SaveCookie impl to Lookup:
            content.add(impl);
        }
        else
        {
            //Otherwise, we remove the SaveCookie impl from the lookup:
            content.remove(impl);
        }
    }

    private class SaveCookieImpl implements SaveCookie
    {
        @Override
        public void save() throws IOException
        {

            Confirmation message = new NotifyDescriptor.Confirmation("Do you want to save \""
                    + iloTextArea.getText() + "\"?",
                    NotifyDescriptor.OK_CANCEL_OPTION,
                    NotifyDescriptor.QUESTION_MESSAGE);

            Object result = DialogDisplayer.getDefault().notify(message);

            //When user clicks "Yes", indicating they really want to save,
            //we need to disable the Save button and Save menu item,
            //so that it will only be usable when the next change is made
            //to the text field:
            if (NotifyDescriptor.YES_OPTION.equals(result))
            {
                fire(false);
                EntityManager entityManager = Persistence.createEntityManagerFactory("KungkhieEntityLibraryPU").createEntityManager();
                entityManager.getTransaction().begin();
                if (ilo.getIloId() != null)
                {
                    Ilo c = entityManager.find(Ilo.class, ilo.getIloId());
                    c.setPackage1(iloPackageTextField.getText());
                    c.setIloText(iloTextArea.getText());
                    c.setNote(notesTextArea.getText());
                    entityManager.getTransaction().commit();
                }
                else
                {

                    ilo.setPackage1(iloPackageTextField.getText());
                    ilo.setIloText(iloTextArea.getText());
                    ilo.setNote(notesTextArea.getText());
                    entityManager.persist(ilo);
                    entityManager.getTransaction().commit();
                }
                IloExplorerTopComponent.refreshNode();
            }

        }
    }
    
    public void clearAndCancel()
    {
       iloPackageTextField.setText("");
       iloTextArea.setText("");
       notesTextArea.setText(""); 
       this.close();
    }
}
